package com.qfedu.fmmall.service.impl;


import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qfedu.fmmall.dao.IndexImgMapper;
import com.qfedu.fmmall.entity.IndexImg;
import com.qfedu.fmmall.entity.ProductImg;
import com.qfedu.fmmall.service.IndexImgService;
import com.qfedu.fmmall.vo.ResultStatus;
import com.qfedu.fmmall.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class IndexImgServiceImpl implements IndexImgService {

    @Autowired
    private IndexImgMapper indexImgMapper;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public ResultVo listIndexImgs() {
        List<IndexImg> list = null;
        try {
            String indexImgs = stringRedisTemplate.boundValueOps("indexImgs").get();
            if(indexImgs != null){
                JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, IndexImg.class);
                list = objectMapper.readValue(indexImgs, javaType);
            }else{

                synchronized (this){
                    String DoubleData = stringRedisTemplate.boundValueOps("indexImgs").get();
                    if(DoubleData == null){
                        list = indexImgMapper.listIndexImgs();
                        stringRedisTemplate.boundValueOps("indexImgs").set(objectMapper.writeValueAsString(list));
                        stringRedisTemplate.boundValueOps("indexImgs").expire(1, TimeUnit.DAYS);
                    }else{//缓存穿透解决方案：当多条请求查询数据库中没有的数据，则在redis中当一条非空的假数据，并让其短时间的内过期
                        ArrayList<Object> arr = new ArrayList<>();
                        stringRedisTemplate.boundValueOps("indexImgs").set(objectMapper.writeValueAsString(arr));
                        stringRedisTemplate.boundValueOps("indexImgs").expire(10,TimeUnit.SECONDS);
                    }

                }

            }

        }catch (Exception e){
            e.printStackTrace();
        }
        if(list.size()==0){
            return  new ResultVo(ResultStatus.NO,"没有轮播图数据哦",null);
        }else{
            return  new ResultVo(ResultStatus.OK,"success",list);
        }
    }
}
